package xjtu.sad.zbsj.task.publisher.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import xjtu.sad.zbsj.dao.task.TaskDao;
import xjtu.sad.zbsj.entity.*;
import xjtu.sad.zbsj.service.*;
import xjtu.sad.zbsj.task.annotater.labelTask.DrawDetail;
import xjtu.sad.zbsj.task.annotater.labelTask.LabelTaskService;
import xjtu.sad.zbsj.task.publisher.Utils.ResultParam;
import xjtu.sad.zbsj.task.publisher.params.DrawListRequestParams;
import xjtu.sad.zbsj.task.publisher.params.TaskListRequestParams;
import xjtu.sad.zbsj.task.publisher.service.TaskService;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("task")
public class TaskController {

    @Autowired
    private TaskService taskService;
    @Autowired
    private LabelTaskService labelTaskService;
    @Autowired
    private TMarkService tMarkService;
    @Autowired
    private TDrawService tDrawService;
    @Autowired
    private TAuditService tAuditService;
    @Autowired
    private TTaskService tTaskService;
    @Autowired
    private TCreditService tCreditService;
    @Resource
    private TaskDao taskDao;


    //添加
    @RequestMapping("addTask")
    public ResultParam<Object> addTask(MultipartFile[] files, String publisher, String type,
                                       String templateId, String taskTitle, String taskRequire,
                                       String taskLimitTime, String taskMarkCount, String taskMaxDistribution,
                                       String taskExceptionTime, String taskDesc, String taskAward) {
        //System.out.println(files.getOriginalFilename()+"="+publisher+"="+type);
        return taskService.addTask(files, publisher, type, templateId, taskTitle, taskRequire, taskLimitTime, taskMarkCount, taskMaxDistribution, taskExceptionTime, taskDesc, taskAward);
    }

    //删除任务
    @RequestMapping("/delTask")
    public ResultParam<Object> delTask(String taskId) {
        return taskService.delTask(taskId);
    }

    //任务列表
    @RequestMapping("/taskList")
    public ResultParam<Object> taskList(TaskListRequestParams taskListRequestParams, @RequestParam Integer userId) {
        return taskService.taskList(taskListRequestParams, userId);
    }

    //右侧领取列表
    @RequestMapping("/drawList")
    public ResultParam<Object> drawList(DrawListRequestParams drawListRequestParams) {
        return taskService.drawList(drawListRequestParams);
    }

    //撤回
    @RequestMapping("/cancel")
    public ResultParam<Object> cancel(String drawId) {
        return taskService.cancel(drawId);
    }

    //结束任务
    @RequestMapping("/end")
    public ResultParam<Object> end(String taskId) {
        return taskService.end(taskId);
    }


    //结束任务
    @RequestMapping("/getDrawDetailById")
    public ResultParam<Object> getDrawDetailById(Integer taskId, @RequestParam List<Integer> markIdList) {
        DrawDetail drawDetailById = labelTaskService.getDrawDetailById(taskId, markIdList);
        ResultParam<Object> objectResultParam = new ResultParam<>();
        objectResultParam.setData(drawDetailById);
        objectResultParam.setStatus(200);
        return objectResultParam;
    }


    //计算正确率 和积分
    @RequestMapping("/rightRate")
    public ResultParam<Object> rightRate(Integer tdrawId, Integer userId) {
        List<TMark> tMarks = tMarkService.queryByDrawId(tdrawId);
        List<TMark> tMarkList = tMarks.stream().filter(tMark -> {
            return "YTG".equals(tMark.getStatus());
        }).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        int sampleNum = taskDao.getSampleNum(tdrawId);
        int i = tMarkList.size() * 100 / sampleNum;
        map.put("rightRate", i);


//        获得的积分：单体奖励*draw_num*正确率
        TDraw tDraw = tDrawService.queryById(tdrawId);
        tDraw.setRightRate(i);

        TTask tTask = tTaskService.queryById(tDraw.getTaskId());
        float score = tTask.getTaskAward() * tDraw.getDrawNum() * i / 100;
        map.put("score", score);
        tDraw.setCredit(score);
        tDrawService.update(tDraw);
        // 添加用户总积分
        TCredit tCredit = tCreditService.queryById(userId);
        tCredit.setTotalCredit(tCredit.getTotalCredit() + score);
        tCreditService.update(tCredit);
        ResultParam<Object> objectResultParam = new ResultParam<>();
        objectResultParam.setData(map);
        objectResultParam.setStatus(200);

        taskDao.updateMarkStatus(tdrawId);
        return objectResultParam;
    }

    /**
     * 点击抽样
     *
     * @param drawId    领取记录id
     * @param sampleNum 抽样数
     * @return 返回抽取出来的数据列表
     */
    @RequestMapping("/sample")
    public ResultParam<Object> getCalResult(Integer drawId, Integer sampleNum) {
        // 获取抽样记录
        TDraw tDraw = tDrawService.queryById(drawId);
        // 修改状态为已审核
        tDraw.setDrawStatus("YSH");
        tDrawService.update(tDraw);
        taskService.updateDrawSample(drawId, sampleNum);// 修改抽样数
//        抽样数：默认显示为draw_num乘5%，但是可以手动在列表里面输入进行修改
        int sample = (int) (tDraw.getDrawNum() * 0.05);
//        正确率：抽样后，mark_status为已通过的/抽样数量
        //获得的积分：单体奖励*draw_num*正确率
//        totalcredict=totalcredict+这次获得的积分（就是上面那个）
        //查询待验收status=2的数据
        List<TMark> tMarks = tMarkService.queryByDrawIdStatus(drawId, "DYS");
        // 对列表进行打乱顺序
        Collections.shuffle(tMarks);
        List<TMark> collect = tMarks.stream().limit(sampleNum).collect(Collectors.toList());
        ResultParam<Object> objectResultParam = new ResultParam<>();
        objectResultParam.setData(collect);
        objectResultParam.setStatus(200);
        return objectResultParam;
    }

    /**
     * 更改tmark表状态
     *
     * @param tmarkId 标注记录
     * @param status  状态 3通过 4不通过
     * @return 返回抽取出来的数据列表
     */
    @RequestMapping("/updateStatus")
    public ResultParam<Object> updateStatus(Integer tmarkId, Integer status, String unpass_reason) {
        TMark tMark = tMarkService.queryById(tmarkId);
        tMark.setStatus(status == 3 ? "YTG" : status == 4 ? "BTG" : "");
        // 修改tmark表状态
        tMarkService.update(tMark);
        TAudit tAudit = new TAudit();
        // 不通过
        if (status == 4) {
            tAudit.setUnpassReason(unpass_reason);
        }
        tAudit.setMarkId(tmarkId);
        // 插入审核表记录
        tAuditService.insert(tAudit);
        ResultParam<Object> objectResultParam = new ResultParam<>();
        objectResultParam.setMsg("成功");
        objectResultParam.setStatus(200);
        return objectResultParam;
    }


    /**
     * 查看异常
     *
     * @param tdrawId 领取记录id
     * @return 返回异常列表
     */
    @RequestMapping("/queryException")
    public ResultParam<Object> queryException(Integer tdrawId) {
        List<TMark> tMarks = tMarkService.queryByDrawId(tdrawId);
        List<TMark> collect = tMarks.stream().filter(tMark -> {
            return tMark.getWarning() == 1;
        }).collect(Collectors.toList());
        ResultParam<Object> objectResultParam = new ResultParam<>();
        objectResultParam.setData(collect);
        objectResultParam.setStatus(200);
        return objectResultParam;
    }

    /**
     * 更改tmark表状态
     *
     * @param tdrawId 领取记录id
     * @return 返回抽取出来的数据列表
     */
    @RequestMapping("/updateDrawStatus")
    public ResultParam<Object> updateDrawStatus(Integer tdrawId, String unpass_reason, Integer tmarkId) {
        TDraw tDraw = tDrawService.queryById(tdrawId);
        tDraw.setDrawStatus("WX");
//        TMark t_Mark = tMarkService.queryById(tmarkId);
//        t_Mark.setStatus("BTG");
        // 修改状态为无效
        tDrawService.update(tDraw);
        // 设置标注详情为不通过
        taskDao.updateMarkStatusBTG(tDraw.getDrawId());
        List<TMark> tMarks = tMarkService.queryByDrawId(tdrawId).stream().filter(tMark -> {
            return tMark.getWarning() == 1;
        }).collect(Collectors.toList());
        ;
        for (TMark tMark : tMarks) {
            TAudit tAudit = new TAudit();
            tAudit.setUnpassReason(unpass_reason);
            tAudit.setMarkId(tMark.getMarkId());

            // 插入审核表记录
            tAuditService.insert(tAudit);
        }
        ResultParam<Object> objectResultParam = new ResultParam<>();
        objectResultParam.setMsg("成功");
        objectResultParam.setStatus(200);
        return objectResultParam;
    }

    /**
     * 更改tmark表Sample
     *
     * @param tDraw
     * @return 返回抽取出来的数据列表
     */
    @RequestMapping("/updateDrawSample")
    public ResultParam<Object> updateDrawSample(@RequestBody TDraw tDraw) {
        taskService.updateDrawSample(tDraw.getDrawId(), tDraw.getSample());
        ResultParam<Object> objectResultParam = new ResultParam<>();
        objectResultParam.setMsg("成功");
        objectResultParam.setStatus(200);
        return objectResultParam;
    }

}
